package servlet;

import dao.entity.CustomerDaoImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/sign_up")
public class SignUpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doGet(req, resp);
        String name=request.getParameter("name");
        String pwd=request.getParameter("pwd");
        String phone=request.getParameter("c_phone");

        CustomerDaoImpl cdi=new CustomerDaoImpl();
        ResultSet rs=cdi.selectUserByName(name);
        boolean is_signed=cdi.isPhoneExisting(phone);
        try {
            if(rs.next()){//用户名已存在
                request.setAttribute("error_code",0);
                request.getRequestDispatcher("user_sign_up.jsp").forward(request,response);
                return;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if(is_signed) {//该手机号已被注册
            request.setAttribute("error_code", 2);
            request.getRequestDispatcher("user_sign_up.jsp").forward(request,response);
            return;
        }
        int n = cdi.addCustomer(name,pwd,phone);
        if(n!=0){
            System.out.println("用户创建/注册成功!");
            request.setAttribute("n",1);//无误
            request.setAttribute("msg","注册成功");
            ServletContext context=getServletContext();
            context.setAttribute("name",name);
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doPost(req, resp);
    }
}
